import { format } from "date-fns";
import { create } from "./object";
import capitalize from "lodash/capitalize";
export const createContent = ({
  id = "",
  control = "",
  title = [],
  value = {},
  config = {}
}) => {
  return {
    control,
    id,
    title,
    value,
    config
  };
};

export const WidgetMap = () => {
  return {
    Selector: {
      type: "select",
      value: "",
      fromContent: content => {
        return content.value.selector.options[0]?.key;
      },
      toContent: (content, value) => {
        const option = content.config.selector.options.find(
          i => i.key === value
        );
        content.value.selector = {
          type: "single",
          op_relations: [],
          options: [option]
        };
        // content.config = "";
      },
      modifier: function(config, value) {
        let options =
          config?.selector?.options || value?.selector?.options || [];
        this.options = options.map(option => {
          return {
            label: option.value[0].text,
            value: option.key
          };
        });
      }
    },
    Text: {
      type: "input",
      value: "",
      fromContent: content => {
        return content.value.text;
      },
      toContent: (content, value) => {
        content.value.text = value;
      }
    },
    Textarea: {
      type: "input",
      value: "",
      props: {
        type: "textarea"
      },
      fromContent: content => {
        return content.value.text;
      },
      toContent: (content, value) => {
        content.value.text = value;
      }
    },
    Number: {
      type: "InputNumber",
      value: "",
      fromContent: content => {
        return parseFloat(content.value.new_number) || 0;
      },
      toContent: (content, value) => {
        content.value.new_number = String(value);
      }
    },
    Money: {
      type: "InputNumber",
      value: "",
      fromContent: content => {
        return parseFloat(content.value.new_money) || 0;
      },
      toContent: (content, value) => {
        content.value.new_money = String(value);
      }
    },
    Date: {
      type: "DatePicker",
      value: "",
      fromContent: content => {
        return format(
          parseInt(content.value.date.s_timestamp) * 1000,
          "yyyy-MM-dd HH:mm:ss"
        );
      },
      toContent: (content, value) => {
        if (!content?.value?.date) {
          create(content, ["value", "date", "s_timestamp"]);
        }
        content.value.date.s_timestamp = String(
          parseInt(new Date(value).getTime() / 1000)
        );
      }
    },
    DateRange: {
      type: "DatePicker",
      valueMap: "date_range",
      props: {
        type: "datetimerange",
        format: "yyyy-MM-dd HH:mm:ss",
        placeholder: "请选择活动日期"
      },

      value: {
        new_begin: 0,
        new_end: 0,
        new_duration: 0
      },
      fromContent: content => {
        const dateRange = content.value.date_range;
        return [
          new Date(dateRange.new_begin * 1000),
          new Date(dateRange.new_end * 1000)
        ];
      },
      toContent: (content, [begin, end]) => {
        if (!content?.value?.date_range) {
          create(content, ["value", "date_range"]);
        }
        const dateRange = content.value.date_range;
        dateRange.new_begin = parseInt(new Date(begin).getTime() / 1000);
        dateRange.new_end = parseInt(new Date(end).getTime() / 1000);
        dateRange.new_duration = dateRange.new_end - dateRange.new_begin;
      }
    },
    File: {
      type: "FormWechatFileList",
      value: [],
      fromContent: ({ id }, extraData) => {
        const files = extraData?.files;
        if (!files || !files[id]) {
          return [];
        }
        return files[id];
      },
      toContent: (content, values = []) => {
        content.value.files = values.map(i => {
          return {
            file_id: i.media_id || i.file_id
          };
        });
      }
    },
    Location: {
      type: "FormPositionPick",
      value: {
        lng: "",
        lat: "",
        address: ""
      },
      fromContent: content => {
        const { location } = content.value;
        const { latitude: lat, longitude: lng, address } = location;
        return {
          lng: parseFloat(lng),
          lat: parseFloat(lat),
          address
        };
      },
      toContent: (content, { lng, lat, address }) => {
        content.value.location = {
          latitude: String(lat),
          longitude: String(lng),
          address,
          title: address,
          time: parseInt(Date.now() / 1000)
        };
      }
    }
  };
};

export const getWeChatData = (applyData, extraData = {}) => {
  const { contents } = applyData;
  const map = WidgetMap();
  const datas = {};
  contents.forEach(({ control, id, value }) => {
    if (map[control]) {
      datas[id] = map[control].fromContent({ value }, extraData);
    }
  });
  return datas;
};

export const getWeChatRules = applyData => {
  const { contents } = applyData;
  const map = WidgetMap();
  const rules = [];
  contents.forEach(({ control, config, value, id: field, title, require }) => {
    control = capitalize(control);
    if (map[control]) {
      const rule = WidgetMap()[control];
      if (rule.modifier) {
        rule.modifier(config, value);
      }
      rules.push({
        ...rule,
        field,
        validate: [{ required: Boolean(require), message: "此处为必填项" }],
        title: title[0]?.text
      });
    }
  });
  return rules;
};

export const getWeChatRulesTemplate = ({ controls: contents }) => {
  return getWeChatRules({
    contents: contents.map(i => {
      return {
        ...i.property,
        config: i.config
      };
    })
  });
};

export const fillWeChatDataTemplate = ({ controls }, values) => {
  const map = WidgetMap();
  const applyData = {
    contents: []
  };
  //   console.log(controls);
  controls.forEach(({ property, config }) => {
    const { control, id, title } = property;
    if (map[control]) {
      const content = createContent({ control, id, title, config });
      map[control].toContent(content, values[id]);
      applyData.contents.push(content);
    }
  });
  return applyData;
};

export const getSummaryListTemplate = (values, editRule = []) => {
  const result = [];
  Object.keys(values).forEach(i => {
    const value = values[i];
    let text = String(value);
    if (text.includes("option")) {
      const rule = editRule.find(rule => rule.field === i);
      text = rule.options.find(opt => opt.value === text)?.label;
    }
    if (text === "[object Object]" || !text) return;
    result.push({
      summary_info: [
        {
          text,
          lang: "zh_CN"
        }
      ]
    });
  });

  return result;
};
